package view;

import controller.UserController;
import model.User;
import util.DatabaseConnection;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 登录界面
 */
public class LoginFrame extends JFrame {
    private JTextField studentIdField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;
    private UserController userController;

    public LoginFrame() {
        userController = new UserController();
        initComponents();
        setupLayout();
        setupEventListeners();
    }

    private void initComponents() {
        setTitle("自习室座位预约系统 - 登录");
        setSize(500, 360);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);

        // 创建输入框 - 设置合适的大小
        studentIdField = new JTextField();
        passwordField = new JPasswordField();

        // 美化输入框
        styleTextField(studentIdField);
        styleTextField(passwordField);

        loginButton = new JButton("登录");
        registerButton = new JButton("注册");

        // 设置现代化按钮样式
        styleButton(loginButton, new Color(24, 144, 255), Color.WHITE); // 蓝色主按钮
        styleButton(registerButton, new Color(255, 255, 255), new Color(102, 102, 102)); // 白色次要按钮
    }

    private void setupLayout() {
        setLayout(new BorderLayout());

        // 设置窗口背景色
        getContentPane().setBackground(new Color(250, 251, 252));

        // 简约标题面板 - 减少高度和边距
        JPanel titlePanel = new JPanel();
        titlePanel.setBackground(new Color(255, 255, 255));
        titlePanel.setPreferredSize(new Dimension(500, 60)); // 从100px减少到60px
        titlePanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(240, 240, 240)),
                BorderFactory.createEmptyBorder(15, 0, 10, 0))); // 添加紧凑的内边距

        JLabel titleLabel = new JLabel("自习室座位预约系统", JLabel.CENTER);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 26));
        titleLabel.setForeground(new Color(64, 64, 64));
        titlePanel.add(titleLabel);

        // 主要内容面板 - 使用简单的垂直布局，减少边距
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        mainPanel.setBackground(new Color(255, 255, 255));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(30, 80, 40, 80)); // 减少上边距从60到30，下边距从60到40

        // 学号输入区域 - 水平布局
        JPanel studentIdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        studentIdPanel.setBackground(new Color(255, 255, 255));
        studentIdPanel.setAlignmentX(Component.CENTER_ALIGNMENT);

        JLabel studentIdLabel = new JLabel("学号：");
        studentIdLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 15));
        studentIdLabel.setForeground(new Color(102, 102, 102));
        studentIdLabel.setPreferredSize(new Dimension(60, 40));

        studentIdField.setPreferredSize(new Dimension(240, 40));

        studentIdPanel.add(studentIdLabel);
        studentIdPanel.add(studentIdField);

        // 密码输入区域 - 水平布局
        JPanel passwordPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        passwordPanel.setBackground(new Color(255, 255, 255));
        passwordPanel.setAlignmentX(Component.CENTER_ALIGNMENT);

        JLabel passwordLabel = new JLabel("密码：");
        passwordLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 15));
        passwordLabel.setForeground(new Color(102, 102, 102));
        passwordLabel.setPreferredSize(new Dimension(60, 40));

        passwordField.setPreferredSize(new Dimension(240, 40));

        passwordPanel.add(passwordLabel);
        passwordPanel.add(passwordField);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
        buttonPanel.setBackground(new Color(255, 255, 255));
        buttonPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
        buttonPanel.add(loginButton);
        buttonPanel.add(registerButton);

        // 组装主面板
        mainPanel.add(studentIdPanel);
        mainPanel.add(Box.createVerticalStrut(15));
        mainPanel.add(passwordPanel);
        mainPanel.add(Box.createVerticalStrut(10));// 添加垂直间距
        mainPanel.add(buttonPanel);

        // 底部提示面板
        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS));
        bottomPanel.setBackground(new Color(250, 251, 252));
        bottomPanel.setPreferredSize(new Dimension(500, 70));
        bottomPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 15, 0));

        JLabel hintLabel = new JLabel("请输入学号和密码登录", JLabel.CENTER);
        hintLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        hintLabel.setForeground(new Color(153, 153, 153));
        hintLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

        JLabel copyrightLabel = new JLabel("制作人：潘梦连   覃彩蜜", JLabel.CENTER);
        copyrightLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
        copyrightLabel.setForeground(new Color(156, 163, 175));
        copyrightLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

        bottomPanel.add(hintLabel);
        bottomPanel.add(Box.createVerticalStrut(5));
        bottomPanel.add(copyrightLabel);

        add(titlePanel, BorderLayout.NORTH);
        add(mainPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);
    }

    private void setupEventListeners() {
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleLogin();
            }
        });

        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                openRegisterDialog();
            }
        });

        // 回车键登录
        getRootPane().setDefaultButton(loginButton);
    }

    private void handleLogin() {
        String studentId = studentIdField.getText().trim();
        String password = new String(passwordField.getPassword());

        if (studentId.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入学号和密码!", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        try {
            // 测试数据库连接
            if (!DatabaseConnection.testConnection()) {
                JOptionPane.showMessageDialog(this, "数据库连接失败，请检查MySQL服务是否启动!",
                        "连接错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            User user = userController.login(studentId, password);
            if (user != null) {
                // 登录成功，打开相应的主界面
                dispose();
                if (user.isAdmin()) {
                    new AdminMainFrame(user).setVisible(true);
                } else {
                    new StudentMainFrame(user).setVisible(true);
                }
            } else {
                JOptionPane.showMessageDialog(this, "学号或密码错误!", "登录失败", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "登录失败: " + ex.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void openRegisterDialog() {
        // 隐藏当前登录窗口
        this.setVisible(false);

        // 创建注册窗口并添加关闭回调
        RegisterDialog dialog = new RegisterDialog(() -> {
            // 注册窗口关闭时重新显示登录窗口
            this.setVisible(true);
        });
        dialog.setVisible(true);
    }

    /**
     * 美化按钮样式 - 简约设计
     */
    private void styleButton(JButton button, Color backgroundColor, Color textColor) {
        // 设置合适的按钮大小，避免挤压
        button.setPreferredSize(new Dimension(120, 45));
        button.setMinimumSize(new Dimension(120, 45));
        button.setMaximumSize(new Dimension(120, 45));

        button.setBackground(backgroundColor);
        button.setForeground(textColor);
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 15));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 简洁的边框
        if (backgroundColor.equals(new Color(255, 255, 255))) {
            // 白色按钮需要边框
            button.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(217, 217, 217), 1),
                    BorderFactory.createEmptyBorder(12, 24, 12, 24)));
        } else {
            // 彩色按钮不需要边框
            button.setBorder(BorderFactory.createEmptyBorder(12, 24, 12, 24));
        }

        // 鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (backgroundColor.equals(new Color(255, 255, 255))) {
                    button.setBackground(new Color(248, 248, 248));
                } else {
                    button.setBackground(backgroundColor.darker());
                }
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(backgroundColor);
            }
        });
    }

    /**
     * 美化输入框样式 - 确保合适的尺寸
     */
    private void styleTextField(JTextField textField) {
        // 设置固定尺寸，避免被挤压
        textField.setPreferredSize(new Dimension(340, 45));
        textField.setMinimumSize(new Dimension(340, 45));
        textField.setMaximumSize(new Dimension(340, 45));

        textField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 15));
        textField.setBackground(new Color(255, 255, 255));

        // 简洁的边框样式
        textField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(217, 217, 217), 1),
                BorderFactory.createEmptyBorder(12, 15, 12, 15)));

        // 聚焦时的边框效果
        textField.addFocusListener(new java.awt.event.FocusListener() {
            @Override
            public void focusGained(java.awt.event.FocusEvent e) {
                textField.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(24, 144, 255), 2),
                        BorderFactory.createEmptyBorder(11, 14, 11, 14)));
            }

            @Override
            public void focusLost(java.awt.event.FocusEvent e) {
                textField.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(217, 217, 217), 1),
                        BorderFactory.createEmptyBorder(12, 15, 12, 15)));
            }
        });
    }
}
